package com.fjeld.middleware.util.collection;

import com.fjeld.middleware.constants.PropertiesManager;
import com.fjeld.middleware.util.serverstatus.ServerStatusCapsule;
import org.apache.log4j.Logger;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;

import javax.swing.*;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: fjeld
 * Date: 16/12/2011
 * Time: 23:50
 * <p/>
 * An observable hash map which monitors the heartbeat server capsule statuses, if any capsules are present.
 */
public class HeartbeatHashmap<K, V> extends ObservableHashMap<K, V>
{
    private Timer timer = null;

    public HeartbeatHashmap()
    {
        super();
    }

    public HeartbeatHashmap(int i)
    {
        super(i);
    }

    @Override
    public V put(K key, V value)
    {
        if (!(value instanceof ServerStatusCapsule))
        {
            throw new IllegalArgumentException("Value must be of type " + ServerStatusCapsule.class.getCanonicalName());
        }

        V val = super.put(key, value);

        if (null == timer)
        {
            int heartbeatUnresponsiveInterval = 5000;
            String interval = PropertiesManager.getProperties().getProperty("Heartbeat.UnresponsiveInterval");
            if (null != interval)
            {
                heartbeatUnresponsiveInterval = Integer.parseInt(interval);
            }
            timer = new Timer(heartbeatUnresponsiveInterval, (ServerStatusCapsule) value);
            timer.setRepeats(true);
            timer.start();
        } else
        {
            timer.addActionListener((ServerStatusCapsule) value);
        }

        return val;
    }

    @Override
    public V remove(Object key)
    {
        return super.remove(key);
    }

    @Override
    public void putAll(Map<? extends K, ? extends V> map)
    {
        throw new NotImplementedException();
    }

    @Override
    public void clear()
    {
        super.clear();
    }
}
